package com.bicon.botu.mall.component.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import com.bicon.botu.core.base.repository.redis.RedisTemplateUtil;
import com.bicon.botu.mall.component.common.InformationConstant;
import com.bicon.botu.mall.component.entity.Information;
import com.bicon.botu.mall.component.mapper.InformationMapper;
import com.bicon.botu.mall.component.service.IInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 系统消息服务实现类
 *
 * @author 张凡
 * @date 2017/12/06 14:36
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements IInformationService {

    @Autowired
    RedisHandler redisHandler;
    @Autowired
    SystemInformationPush systemInformationPush;
    @Autowired
    InformationMapper informationMapper;


    /**
     * 保存系统消息
     *
     * @param appId      app标识
     * @param userIdJson 多个用户id
     * @param module     模块
     * @param business   子模块
     * @param title      标题
     * @param content    内容
     * @param headline   首页标题
     * @param push       是否推送
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String appId, String userIdJson, String module, String business, String title, String content, String headline, String push) {
        String[] userIds = userIdJson.split(",");
        List<Information> informationList = new ArrayList<>();
        for (int i = 0; i < userIds.length; i++) {
            Information information = new Information();
            information.preInsert();
            information.setContent(content);
            information.setModule(module);
            information.setBusiness(business);
            information.setTitle(title);
            information.setHeadline(headline);
            information.setAppId(appId);
            information.setUserId(userIds[i]);
            informationList.add(information);
        }
        if (!CollectionUtils.isEmpty(informationList)) {
            boolean result = insertBatch(informationList);
            if (!result) {
                throw new BusinessException(InformationConstant.RESPONSE_CODE_500, InformationConstant.RESPONSE_MESSAGE_500);
            }
            //存到缓存上
            RedisTemplateUtil redisTemplateUtil = redisHandler.getGlobalRedisTemplate();
            informationList.stream().forEach(information -> {
                redisTemplateUtil.cacheZSet(InformationConstant.INFORMATION_REDIS_KEY, information.getUserId(),
                        JSONObject.toJSONString(information), Double.valueOf(JSONArray.toJSONString(information.getCreateDate())));
            });

        }
        //推送
        if (InformationConstant.PUSH.equals(push)) {
            HashMap<String, String> map = new HashMap<>(16);
            map.put("type", InformationConstant.SYSTEM_INFORMATION_TYPE + module);
            map.put("headline", headline);
            systemInformationPush.systemInformationPush(userIds, map);
        }
    }

    /**
     * 初始化系统消息
     */
    @Override
    public void init() {
        RedisTemplateUtil redisTemplateUtil = redisHandler.getGlobalRedisTemplate();
        //移除缓存
        List<Information> list = new Information().selectList(new EntityWrapper<Information>().groupBy("user_id"));
        if (!CollectionUtils.isEmpty(list)) {
            for (Information information : list) {
                String userId = information.getUserId();
                redisTemplateUtil.remove(InformationConstant.INFORMATION_REDIS_KEY, userId);
            }
        }
        List<Information> informationList = informationMapper.initSystemInformation();
        //存到缓存上
        if (!CollectionUtils.isEmpty(informationList)) {
            for (Information information : informationList) {
                String userId = information.getUserId();
                redisTemplateUtil.cacheZSet(InformationConstant.INFORMATION_REDIS_KEY, userId,
                        JSONObject.toJSONString(information), Double.valueOf(JSONArray.toJSONString(information.getCreateDate())));
            }
        }
    }
}
